﻿using Microsoft.Data.Sqlite;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Launchkit_Backend.model;
using System.Drawing;
using ICSharpCode.SharpZipLib.Zip;

namespace Launchkit_Backend
{
    static class Program
    {
        public static SqliteConnection db;
        public const string DbFileName = "data.db";


        [STAThread]
        static void Main()
        {
            Environment.CurrentDirectory = Path.GetDirectoryName(Application.ExecutablePath);
            initDb();
            initFile();
            EntryActions.init();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
            DBUtils.destory();
            db.Close();
        }

        static void initDb() {
            bool initDb = false;
            if (!File.Exists(DbFileName))
            {
                initDb = true;
                File.WriteAllBytes(DbFileName, Properties.Resources.TemplateDB);
            }
            db = new SqliteConnection("DataSource="+DbFileName+";");
            db.Open();
            DBUtils.conn = db;
            DBUtils.Init();
            if (initDb)
            {
                DBUtils.InitDB();
            }
        }

        static void initFile() {
            checkLibrary();
        }

        public const string appid = "com.zyfdroid.launchkit_v100000000";

        public static IconProvider IconProvider;

        public static void checkLibrary()
        {
            String rootpath = Path.Combine(Path.GetTempPath(), appid, "libs");
            String pluginpath = Path.Combine(rootpath, "plugins");
            makeFileExists(Properties.Resources.icon3, Path.Combine(rootpath, "icon3.pak"));
            IconProvider = new IconProvider(new MyPakFile(Path.Combine(rootpath, "icon3.pak")));
        }

        public static void makeFileExists(byte[] data, String filename)
        {
            if (!Directory.Exists(Path.GetDirectoryName(filename)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(filename));
            }
            if (!File.Exists(filename))
            {
                File.WriteAllBytes(filename + ".tmp", data);
                File.Move(filename + ".tmp", filename);
            }
        }
    }

    public class IconProvider {
        public const string ic_exec = "description.png";
        public const string ic_dir = "folder.png";
        public const string ic_cmd = "playlist_play.png";
        public const string ic_url = "language.png";

        MyPakFile file;

        public List<String> IconList { get => file.files; }

        public IconProvider(MyPakFile file)
        {
            this.file = file;
            
        }
        Dictionary<string, Image> cachedImage = new Dictionary<string, Image>();

        public Image GetIcon(string name) {

            if (cachedImage.ContainsKey(name))
            {
                try
                {
                    cachedImage[name].Size.ToString();
                    return cachedImage[name];
                }
                catch (Exception ex) {
                    Console.WriteLine(ex);
                }
            }
            try {
                if (name.Contains("/") || name.Contains("\\"))
                {
                    Icon i = Icon.ExtractAssociatedIcon(name);
                    return new Bitmap(i.ToBitmap(), 24, 24);
                }
            }catch(Exception e)
            {
                name = ic_exec;
            }
            using (Stream s = file.OpenRead(name)) {
                try
                {
                    Image i = Image.FromStream(s);
                    cachedImage.Add(name, i);
                    return i;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
            return null;
        }
    }

    class BorderlessButton : Button {
        public BorderlessButton() : base() {
            this.FlatStyle = FlatStyle.Flat;
            this.ForeColor = Color.White;
            this.FlatAppearance.BorderSize = 0;
            this.BackColor = Color.Transparent;
            this.FlatAppearance.MouseOverBackColor = Color.FromArgb(72, 255, 255, 255);
            this.FlatAppearance.MouseDownBackColor = Color.FromArgb(127, 0,0,1);
        }
    }


    public class MyPakFile : IDisposable
    {
        public string Tag = "";
        public List<string> files = new List<string>();
        ZipFile src;
        public MyPakFile(string path)
        {
            ICSharpCode.SharpZipLib.Zip.ZipStrings.UseUnicode = true;
            src = new ZipFile(path);
            System.Collections.IEnumerator en = src.GetEnumerator();
            while (en.MoveNext())
            {
                ZipEntry ze = en.Current as ZipEntry;
                if (ze != null)
                {
                    files.Add(ze.Name);
                    Console.WriteLine(ze.Name);
                }
            }
        }

       
        public Stream OpenRead(string filename)
        {
            
            if (files.Contains(filename) && !filename.EndsWith("/"))
            {
                ZipEntry ze = src.GetEntry(filename);
                return src.GetInputStream(ze);
            }
            return null;
        }

        public void Dispose()
        {
            ((IDisposable)src).Dispose();
        }
    }
}
